#
# LuckyBot4, a python IRC bot
# (c) Copyright 2008 by Lucas van Dijk
# http://www.return1.net
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA
#
# $Id: main.py 29 2009-02-11 15:44:45Z luckyluke56 $
#

import os
import re
import luckybot
from luckybot.luckynet.protocols import irc
from luckybot import bot
import luckybot.bot.plugins as plugins
import luckybot.bot.auth as auth
import luckybot.path as path
from ConfigParser import SafeConfigParser

class LuckyBot(object):
	"""
		This is the main bot class, where every thing is controlled from
	"""

	def __init__(self, options, args):
		"""
			Initializes the bot, reads settings, and setups auth/plugin manager
		"""

		self.view = None

		# Load settings
		self.settings = SafeConfigParser()
		if os.path.exists(path.get_personal_file('settings.ini')):
			self.settings.read([path.get_personal_file('settings.ini')])
		else:
			self.settings.read(path.get_base_path('data', 'settings.ini'))

		self.plugins = plugins.Manager(self)
		self.auth = auth.Manager()
		self.options = options
		self.args = args

	def set_view(self, view):
		"""
			This sets the view for the bot

			@type view: views.base.BaseView
			@param view: The view for the bot, which displays all info on the screen
		"""
		self.view = view

		self.plugins.load_plugins(luckybot.path.get_base_path('plugins'))
		self.plugins.load_plugins(luckybot.path.get_personal_file('plugins'))

		self.view.set_bot(self)

	def get_servers(self):
		"""
			Reads the configuration file, and checks which servers
			to connect to
		"""

		servers = []
		sections = self.settings.sections()
		regexp = re.compile(r'^Server(\d+)$', re.I)

		for section in sections:
			match = regexp.match(section)
			if match:
				config = {}
				for option in self.settings.options(section):
					config[option] = self.settings.get(section, option)
				servers.append(config)

		return servers

	def on_message(self, protocol, event):
		"""
			Calls plugin handler to check for called plugins
		"""

		self.plugins.check_data(event)


